package com.pagoda.nerp.trade.admin.system.web;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pagoda.nerp.trade.common.BaseResult;
import com.pagoda.nerp.trade.common.GridDataResult;
import com.pagoda.nerp.trade.common.enums.ErrorCodeMappingEnums;
import com.pagoda.nerp.trade.entity.AccModule;
import com.pagoda.nerp.trade.entity.AccRole;
import com.pagoda.nerp.trade.entity.AccUsers;
import com.pagoda.nerp.trade.service.ModuleService;
import com.pagoda.nerp.trade.service.RoleService;
import com.pagoda.nerp.trade.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by dell on 2016/11/22.
 */
@Controller
@RequestMapping("/users")
public class UserController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ModuleService moduleService;


    /**
     * 查询系统用户信息 (mobileCode,userCode)
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryUser", method = RequestMethod.POST)
    public BaseResult<AccUsers> queryAccUser(@RequestBody Map<String, String> map) {

        //参数校验
        if ((map.get("userCode")) == null || "".equals(map.get("userCode")) && (map.get("mobileCode") == null || "".equals(map.get("mobileCode")))) {
            logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorMsg());
            return new BaseResult<>( ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
        }
        AccUsers user = userService.queryAccUser(map);
        if (user == null) {
            logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD.getErrorMsg());
            return new BaseResult<>(ErrorCodeMappingEnums.ERROR_EXCEPTION_USERS);
        }

        return new BaseResult<AccUsers>(ErrorCodeMappingEnums.SUCCESS, user);
    }


    /**
     * 用户信息列表
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryUserList", method = RequestMethod.POST)
    public BaseResult<List<AccUsers>> getUserList(@RequestBody Map<String, String> map) {

        //分页设置
        int pageNo = map.get("pageNo") == null ? 1 : Integer.valueOf(map.get("pageNo"));
        int pageSize = map.get("pageSize") == null ? 10 : Integer.valueOf(map.get("pageSize"));
        Page page = PageHelper.startPage(pageNo, pageSize, true);//开始分页,并统计总数

        //查询用户列表
        List<AccUsers> userList = userService.queryAccUserList(map);
        if (userList == null || userList.size() == 0) {
            logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD.getErrorMsg());
            return new BaseResult<>(ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD);
        }

        return new GridDataResult<List<AccUsers>>(ErrorCodeMappingEnums.SUCCESS, userList, (int) page.getTotal());

    }

    /**
     * 支持批量删除用户信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteUsers", method = RequestMethod.POST)
    public BaseResult deleteUsers(@RequestBody Map<String, String> map) {

        //参数校验
        if (map.get("userIds") == null || "".equals(map.get("userIds"))) {
            logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorMsg());
            return new BaseResult(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
        }

        //解析参数
        String[] userIdsArray = map.get("userIds").split(",");
        List<Integer> userIdList = new ArrayList<Integer>();
        for (String userId : userIdsArray) {
            userIdList.add(Integer.valueOf(userId));
        }

        int i = userService.deleteUsers(userIdList);
        if (i <= 0) {
            logger.error(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML.getErrorMsg());
            return new BaseResult<>(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML);
        }

        //删除成功返回
        return new BaseResult(ErrorCodeMappingEnums.SUCCESS);
    }


    /**
     * 新增用户 (返回用户ID）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public BaseResult addUser(@RequestBody AccUsers AccUsers) {


        //参数校验
        if (AccUsers == null) {
            logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorMsg());
            return new BaseResult(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
        }

        int i = userService.addUser(AccUsers);
        if (i <= 0) {
            logger.error(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML.getErrorMsg());
            return new BaseResult(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML);
        }

        return new BaseResult<Integer>(ErrorCodeMappingEnums.SUCCESS, AccUsers.getUserId());
    }

    /**
     * 根据userId更新用户
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUser")
    public BaseResult updateUser(@RequestBody AccUsers accUsers) {

        //参数校验
        if (accUsers == null) {
            logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorMsg());
            return new BaseResult<>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
        }

        int i = userService.updateUser(accUsers);
        if (i <= 0) {
            logger.error(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML.getErrorMsg());
            return new BaseResult<>(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML);
        }

        return new BaseResult(ErrorCodeMappingEnums.SUCCESS);
    }

    /**
     * 绑定用户和角色
     *
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/bindUserRelRole")
    public BaseResult bindUserRelRole(@RequestBody Map<String,String> map) {
        try {

            //参数校验
            if (StringUtils.isEmpty(map.get("userIds")) || StringUtils.isEmpty(map.get("roleIds"))) {
                logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorMsg());
                return new BaseResult(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
            }

            //插入数据库
            int i = userService.bindUserAndRole(map);
            if (i <= 0) {
                logger.error(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML.getErrorMsg());
                return new BaseResult(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML);
            }

        } catch (Exception e) {
            logger.error("Batch bind user and role failed,exception={}",e);
            return new BaseResult(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML);
        }

        return new BaseResult(ErrorCodeMappingEnums.SUCCESS);
    }


    /**
     * 新增角色
     *
     * @param accRole
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addRole")
    public BaseResult addRole(@RequestBody AccRole accRole) {

        //参数校验
        if (accRole == null) {
            logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorMsg());
            return new BaseResult( ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
        }

        int i = roleService.addRole(accRole);
        if (i <= 0) {
            logger.error(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML.getErrorMsg());
            return new BaseResult( ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML);
        }

        return new BaseResult<Integer>(ErrorCodeMappingEnums.SUCCESS, accRole.getRoleId());
    }

    /**
     * @param accRole
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateRole")
    public BaseResult updateRole(@RequestBody AccRole accRole) {

        //参数校验
        if (accRole == null) {
            logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorMsg());
            return new BaseResult<>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
        }

        int i = roleService.updateRole(accRole);
        if (i <= 0) {
            logger.error(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML.getErrorMsg());
            return new BaseResult( ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML);
        }

        return new BaseResult(ErrorCodeMappingEnums.SUCCESS);
    }


    /**
     * 查询单个用户信息  (roleId, roleCode)
     *
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryRole")
    public BaseResult queryRole(@RequestBody Map<String, String> map) {

        //参数校验
        if ((map.get("roleId") == null && map.get("roleCode") == null)) {
            logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorMsg());
            return new BaseResult<>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
        }

        AccRole role = roleService.queryRoleByRoleIdOrRoleCode(map);
        if (role == null) {
            logger.error(ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD.getErrorMsg());
            return new BaseResult(ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD);
        }

        return new BaseResult<AccRole>(ErrorCodeMappingEnums.SUCCESS, role);
    }


    /**
     * 查询角色信息列表
     *
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryRoleList")
    public BaseResult<List<AccRole>> queryRoleList(@RequestBody Map<String,String> map) {

        //参数校验
        if (map == null) {
            logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorMsg());
            return new BaseResult<>( ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
        }

        //分页设置
        int pageNo = map.get("pageNo") == null ? 1 : Integer.valueOf(map.get("pageNo"));
        int pageSize = map.get("pageSize") == null ? 10 : Integer.valueOf(map.get("pageSize"));
        Page page = PageHelper.startPage(pageNo, pageSize, true);//开始分页,并统计总数

        String roleName = map.get("roleName") != null ? map.get("roleName").toString() : "";
        List<AccRole> roleInfoList = roleService.queryRoleListByRoleName(roleName);
        if (roleInfoList == null || roleInfoList.size() == 0) {
            logger.error(ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD.getErrorMsg());
            return new BaseResult<>( ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD);
        }

        return new GridDataResult<List<AccRole>>(ErrorCodeMappingEnums.SUCCESS, roleInfoList, (int)page.getTotal());
    }

    /**
     * 查询功能模块
     *
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryModule")
    public BaseResult<List<AccModule>> queryModuleInfoList(@RequestBody Map<String, String> map) {

        //参数校验
        if (map == null || map.get("roleId")==null ||map.get("userId") == null) {
            logger.debug(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorMsg());
            return new BaseResult<>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
        }

        List<AccModule> moduleInfosList = moduleService.queryModuleListByUserIdAndRoleId(map);
        if (moduleInfosList == null || moduleInfosList.size() == 0) {
            logger.error(ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD.getErrorMsg());
            return new BaseResult<>( ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD);
        }

        return new BaseResult<List<AccModule>>(ErrorCodeMappingEnums.SUCCESS, moduleInfosList);

    }

}
